package scala.day03

import scala.io.Source

object Demo04StudentTest {
  def main(args: Array[String]): Unit = {
    /**
      *  1、统计总分年级排名前十学生各科的分数
      */
    //读取成绩表
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList
    //读取学生表
    val students: List[String] = Source.fromFile("data/students.txt").getLines().toList
    //读取科目表
    val cources: List[String] = Source.fromFile("data/cource.txt").getLines().toList
    //取出id和成绩
    val idAndScore: List[(String,Double)] = scores.map(f => {
      val split: Array[String] = f.split(",")
      (split(0),split(2).toDouble)
    })
    //取出学生id和name
    val idAndName: List[(String, String)] = students.map(f => {
      val split: Array[String] = f .split(",")
      (split(0),split(1))
    })
    //取出科目id和科目名称
    val cidAndCname: List[(String, String)] =cources.map(f =>{
      val split: Array[String] = f.split(",")
      (split(0),split(1))
    })
    //按照id分组
    val group: Map[String, List[(String, Double)]] = idAndScore.groupBy(i => i._1)
    //求总分
    val idAndSum: Map[String, Double] = group.map(kv => {
      val id: String = kv._1//id
      //取出一个人所有的科目成绩
      val scoreNum: List[Double] = kv._2.map(kv1 => kv1._2)
      val sum: Double = scoreNum.sum
      (id,sum)
    })
    val idNameAndScore: List[(String,String, Double)] = idAndName.map(f => {
      val id: String = f._1//id
      val name: String = f._2//姓名
      val score: Double = idAndSum.getOrElse(id,0)
      (id,name,score)
    })
    //将成绩降序排序，并取出前10名
    val Top10: List[(String, String, Double)] = idNameAndScore.sortBy(i => -i._3).take(10)
    //取出前十的id
    val ids: List[String] = Top10.map(f => f._1)
    //在scores中过滤数据
    val idFilter: List[String] = scores.filter(p =>{
      val split: Array[String] = p.split(",")
      val id: String = split(0)
      ids.contains(id)
    })
    //将学号换成姓名,科目id换成科目名称
    idFilter.map(f =>{
      val split: Array[String] = f.split(",")
      val id: String = split(0)
      val cid: String = split(1)
      val score: String = split(2)
      val name: String = idAndName.toMap.getOrElse(id,"null")
      val cname: String = cidAndCname.toMap.getOrElse(cid,"null")
      (name,cname,score)
    }).foreach(println)
  }
}
